package com.show.mybatis.utils;

import com.show.mybatis.config.Mapper;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Executor {

    public static<T> List<T> selectList(Mapper mapper, Connection connection) {
        List<T> reuslts = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            reuslts = new ArrayList<>();

            String sql = mapper.getQueryString();

            Class<?> clazz = Class.forName(mapper.getResultType());

            pstmt = connection.prepareStatement(sql);

            rs = pstmt.executeQuery();

            ResultSetMetaData metaData = rs.getMetaData();

            int columnCount = metaData.getColumnCount();

            while (rs.next()){

                T obj = (T) clazz.newInstance();

                for (int i = 1; i <= columnCount; i++) {

                    String columnName = metaData.getColumnName(i);

                    Object value = rs.getObject(columnName);

                    PropertyDescriptor descriptor = new PropertyDescriptor(columnName, clazz);

                    Method writeMethod = descriptor.getWriteMethod();

                    writeMethod.invoke(obj,value);
                }

                reuslts.add(obj);
            }
            return reuslts;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            close(connection,pstmt,rs);
        }
    }

    public static void close(Connection connection, Statement stmt,ResultSet rs){
        try {
            if (rs != null){
                rs.close();
            }
            if (stmt != null){
                stmt.close();
            }
            if (connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
